import json
from typing import Any, Dict, Optional


class ApiResponse:
    """API响应封装类"""

    def __init__(self, response):
        self.response = response
        self.status_code = response.status_code
        self.headers = response.headers
        self._json_data = None

    @property
    def success(self) -> bool:
        """判断请求是否成功"""
        if self.status_code == 200:
            try:
                data = self.json()
                return data.get('success', False)
            except:
                return False
        return False

    def json(self) -> Dict[str, Any]:
        """获取JSON格式的响应数据"""
        if self._json_data is None:
            try:
                self._json_data = self.response.json()
            except json.JSONDecodeError:
                self._json_data = {}
        return self._json_data

    def get_data(self, key: Optional[str] = None) -> Any:
        """获取响应数据"""
        data = self.json()
        if key:
            return data.get('data', {}).get(key) if 'data' in data else None
        return data.get('data')

    def get_message(self) -> str:
        """获取响应消息"""
        data = self.json()
        return data.get('message', '')

    def raise_for_status(self):
        """如果响应状态码表示错误，则抛出异常"""
        if not self.success:
            raise ApiException(f"API请求失败: {self.get_message()}")